<?php
define("CCTRL", "users");
define("CCTRLNAME", "users");
define("TOKEN", "bb6222905ef8419183b5437779497596");
class user extends BACKEND_Controller {
    /*
      Project     : 48c6c450f1a4a0cc53d9585dc0fee742
      Created on  : Mar 16, 2013, 11:29:15 PM
      Author      : Truong Khuong - khuongxuantruong@gmail.com
      Description :
      Purpose of the stylesheet follows.
     */
    private $assets=null;
    function __construct() {
        parent::__construct();
        $this->load->model('backend/user_model');
        $this->smarty = new CI_Smarty3();
        $this->smarty->error_reporting = E_ALL & ~E_NOTICE;
        if (!isset($_SESSION["ADP"][CCTRL]["display"]))
            $_SESSION["ADP"][CCTRL]["display"] = 0;
    }

    function index() {
        $assigns['menuactive']='menu-user';
        
        $colModel = $this->user_model->colmod();
        foreach ($colModel as $col) {
            $datafields[] = array(
                'name' => $col['datafield'],
                'type' => isset($col['type']) ? $col['type'] : 'string'
            );
            $column = $col;
            $column['editable'] = isset($col['editable']) ? $col['editable'] : false;
            $column['filterable'] = isset($col['filterable']) ? $col['filterable'] : true;
            $column['sortable'] = isset($col['sortable']) ? $col['sortable'] : true;
            $column['minwidth'] = isset($col['minwidth']) ? $col['minwidth'] : (isset($col['width']) ? $col['width'] : 100);
            $columns[$col['datafield']] = $column;
            $list[] = array(
                'label' => $col['text'],
                'value' => $col['datafield'],
                'checked' => isset($col["hidden"]) ? !$col["hidden"] : true
            );
        }
        $assigns['datafields']= $datafields;
        $assigns['columns']= $columns;
        $assigns['list']= $list;
        $type=isset($_GET['type'])?$_GET['type']:null;
        $assigns['bindingsource']=base_url()."/backend/user/binding";
        
        $assigns['users'] = $this->user_model->gets();
        $this->smarty
                ->assign($assigns)
                //->display("admin/01_auth_user");
                ->display("backend/02_user/01_grid");
    }

    function editor($id = "") {
        if ($id !== "")
            $this->assets['user'] = $this->user_model->get($id);
        $this->load->view('views_backend/user/02_user_edit_panel',$this->assets);
        
//        $this->smarty
//                ->assign($assigns)
//                ->display("backend/02_user/editor");
    }
    function binding() {
        $result = $this->user_model->binding();
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($result));
    }
    function randomstring(){
        echo random_string('alnum', rand(4, 8)*2);
    }
    
    function save() {
        $R["result"] = -1;
        $R["message"] = ascii_to_entities("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if($this->privilege->aupr_permission!=777)goto result;
        
        $params["ause_name"] = $this->input->post("ause_name");
        $params["ause_username"] = $this->input->post("ause_username");
        $params["ause_position"] = (int) $this->input->post("ause_position");
        $params["ause_status"] = $this->input->post("ause_status");
        $params["ause_email"] = $this->input->post("ause_email");
        $apri_id = $this->input->post("ause_id");
        if ($apri_id != false) {
            $user = $this->user_model->get($apri_id);
            if($user==null){
                $R["result"] = -904;
                $R["message"] = ascii_to_entities("User not exist."); 
                goto result;
            }
            if($this->input->post("ause_password")!=false){
                $params["ause_password"]=md5($params["ause_username"].$this->input->post("ause_password").$user->ause_secretkey);
            }
            $params["ause_update"] = date('Y-m-d H:i:s');
            $rok = @$this->user_model->update($apri_id, $params);
        } else {
            $params["ause_key"] = random_string('alnum', 8);
            $params["ause_salt"] = random_string('alnum', 8);
            $params["ause_secretkey"] = random_string('alnum', 32);
            $params["ause_password"]=md5($params["ause_username"].$this->input->post("ause_password").$params["ause_secretkey"]);
            $rok = @$this->user_model->insert($params);
        }
        if ($rok === true) {
            $R["result"] = 1;
            $R["message"] = ascii_to_entities("Dữ liệu đã được hệ thống ghi nhận.");
        } else {
            $R["result"] = -1;
            $R["error_number"] = $this->db->_error_number();
            $R["error_message"] = $this->db->_error_message();
            $R["message"] = ascii_to_entities("
                    Dữ liệu chưa được hệ thống ghi nhận.<br/>
                    Vui lòng kiểm tra dữ liệu và thử lại.<br/>
                    ");
            if ($R["error_number"] != 0)
                $R["message"].=ascii_to_entities("<span class='erc'>[" . $R["error_number"] . "] " . $R["error_message"] . ".</span>");
        }
        result:
        echo json_encode($R);
    }
    function detail($id = "") {
        //$id=$this->input->get('id');
        $user = $this->user_model->get($id);
        if ($user === null)
            show_404();
        $privileges = $this->user_model->getprivileges($id);
        //echo $this->db->last_query();
        $time = time();
        $salt = $_SESSION['auth']['user']->ause_salt;
//        $this->smarty
//                ->assign(array(
//                    'user' => $user,
//                    'privileges' => $privileges,
//                    'time' => $time,
//                    'salt' => $salt
//                ))
//                ->display("backend/02_user/01_detail");
        $this->assets=array(
                    'user' => $user,
                    'privileges' => $privileges,
                    'time' => $time,
                    'salt' => $salt
                );
        $this->load->view('views_backend/user/01_user_privilege',$this->assets);
    }
    function setprivilege() {
        $R["result"] = -1;
        $R["message"] = ascii_to_entities("This function to requires an administrative account.<br/>Please check your authority, and try again.");
        if($this->privilege->aupr_permission!=777)goto result;
        $R["result"] = -998;
        $rOk = 0;
        $R["message"] = ascii_to_entities("Access is denied - Request invalid.");
        $salt = $_SESSION['auth']['user']->ause_salt;
        $aupr_user = $this->input->post('user_id');
        $aupr_privilege = $this->input->post('privilege_id');
        $aupr_permission = $this->input->post('permission');
        $secretkey = $this->input->post('secretkey');
        $signature = $this->input->post('signature');
        if ($this->privilege->aupr_permission !== '777') {
            $R["result"] = -997;
            $R["message"] = ascii_to_entities("Permission denied to access the function.");
            goto result;
        }
        //if( $signature!==md5("$aupr_privilege$secretkey$salt") ){
        //	$R["result"]=-991;
        //	$R["message"]=ascii_to_entities("Signature invalid.");
        //	goto result;
        //}
        $aParamsi = array(
            'aupr_user' => $aupr_user,
            'aupr_privilege' => $aupr_privilege,
            'aupr_permission' => $aupr_permission,
            'aupr_insert' => date('Y-m-d H:i:s'),
            'aupr_status' => 'true',
        );
        $aUpdate = array('aupr_permission', 'aupr_insert');
        $rOk = $this->user_model->insert_onduplicate_update_aupr($aParamsi, $aUpdate);
        if ($rOk > 0) {
            $R["result"] = 1;
            $R["message"] = ascii_to_entities("Set permission success.");
        } else {
            $R["result"] = -1;
            $R["message"] = ascii_to_entities("Set permission fail.");
        }
        result:
        $this->output->set_header('Content-type: application/json');
        $this->output->set_output(json_encode($R));
    }
}

?>